import java.util.LinkedList;
import java.util.Queue;

class Solution {

    int m;
    int n;
    boolean[][] visited;
    int[] dx = {1,-1,0,0};
    int[] dy = {0,0,1,-1};

    public int[][] highestPeak(int[][] isWater) {
        m = isWater.length;
        n = isWater[0].length;
        Queue<int[]> queue = new LinkedList<>();
        visited = new boolean[m][n];
        int[][] map = new int[m][n];
        // 1、将水域加入队列中
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (isWater[i][j] == 1) {
                    queue.offer(new int[]{i, j});
                    map[i][j] = 0;
                    visited[i][j] = true;
                }
            }
        }
        // 2、对队列进行多源BFS
        while (!queue.isEmpty()) {
            int[] arr = queue.poll();
            for (int k = 0; k < 4; k++) {
                int sr = arr[0] + dx[k], sc = arr[1] + dy[k];
                if (sr >= 0 && sr < m && sc >= 0 && sc < n && !visited[sr][sc]) {
                    map[sr][sc] = map[arr[0]][arr[1]] + 1;
                    queue.offer(new int[]{sr, sc});
                    visited[sr][sc] = true;
                }
            }
        }
        return map;
    }
}